<script setup lang="ts">
import { ref, h, reactive } from "vue";
import {
  getRoleList,
  queryRoleList,
  addAgentByAgent,
  editRole,
  removeAgentByAgent,
  resetRolePassword,
  enums
} from "@/api/system";
import { uploadUrl } from "@/api/global";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ComponentSize } from "element-plus";
import type { UploadProps } from "element-plus";
defineOptions({
  name: "system"
});
const size = ref<ComponentSize>("default");
const currentPage = ref(1);
const pageSize = ref(10); // 添加这行
const background = ref(false);
const disabled = ref(false);
const pageTotal = ref(0);
let tableData = ref([]);
const type = ref("");
let previewQrCodeUrl = ref("");
let previewUrl = ref("");
const queryParams = reactive({
  userName: "",
  phoneNum: "",
  roleId: ""
});
// 在文件开头的 ref 定义部分添加
const deleteFlagList = ref([]);
// enums({ code: "TrueFalse" }).then((res: any) => {
//   deleteFlagList.value = res.data;
// });
// 角色列表
const roleList = ref([]);
const addRoleDialogVisible = ref(false);
getRoleList().then((res: any) => {
  roleList.value = res.data;
});
//性别
const genderList = ref([]);
enums({ code: "Gender" }).then((res: any) => {
  genderList.value = res.data;
});

function handleAddRole(mark) {
  addRoleDialogVisible.value = true;
  type.value = mark;
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = key === "roleIds" ? [] : "";
  });
}
const ruleFormRef = ref<FormInstance>();

const validatephoneNum = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else {
    if (ruleForm.phoneNum !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("phoneNum");
    }
    callback();
  }
};
const ruleForm = reactive({
  phoneNum: "", //true
  userName: "", //true
  gender: "", //true
  loginNo: "", //true
  roleIds: [], //true
  enterTime: "", //true
  avatar: "",
  birthday: "",
  email: "",
  qrCode: ""
});

const rules = reactive<FormRules<typeof ruleForm>>({
  phoneNum: [{ required: true, validator: validatephoneNum, trigger: "blur" }],
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  loginNo: [{ required: true, message: "请输入账号", trigger: "blur" }],
  enterTime: [{ required: true, message: "请选择录入时间", trigger: "change" }]
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("submit!");
      if (type.value == "add") {
        addAgentByAgent({
          userName: ruleForm.userName,
          phoneNum: ruleForm.phoneNum,
          roleIds: ruleForm.roleIds.join(","), // 将数组转换为逗号分隔的字符串
          gender: ruleForm.gender,
          loginNo: ruleForm.loginNo,
          enterTime: ruleForm.enterTime,
          avatar: ruleForm.avatar,
          birthday: ruleForm.birthday,
          email: ruleForm.email,
          qrCode: ruleForm.qrCode
        }).then((res: any) => {
          console.log(res);
          ElMessage({
            type: "success",
            message: res.message
          });
          addRoleDialogVisible.value = false;
          queryListTableData();
        });
      } else if (type.value == "edit") {
        editRoleInfo();
      }
    } else {
      console.log("error submit!");
    }
  });
};

//初始化列表
queryListTableData();
//查询列表
function queryListTableData(params?) {
  const _params = {
    pageNo: 1,
    pageSize: 10,
    total: 0,
    ...params
  };
  if (queryParams.userName) {
    _params.userName = queryParams.userName;
  }
  if (queryParams.phoneNum) {
    _params.phoneNum = queryParams.phoneNum;
  }
  if (queryParams.roleId) {
    _params.roleId = queryParams.roleId;
  }
  queryRoleList({ ..._params }).then((res: any) => {
    console.log(res, "res");
    tableData.value = res.data.data;
    pageTotal.value = res.data.total;
  });
}

// 重置页面
const onReset = () => {
  queryParams.userName = "";
  queryParams.phoneNum = "";
  queryParams.roleId = "";
  pageTotal.value = 0;
  currentPage.value = 1;
  queryListTableData();
};
const editId = ref("");
const handleEditRole = async (row, mark) => {
  console.log(row.value, "data");
  previewUrl.value = "";
  previewQrCodeUrl.value = "";
  type.value = mark;
  editId.value = row.id;
  addRoleDialogVisible.value = true;
  ruleForm.phoneNum = row.phoneNum;
  ruleForm.userName = row.userName;
  ruleForm.roleIds = row.roles ? row.roles.map(role => role.id) : [];
  ruleForm.gender = row.gender;
  ruleForm.loginNo = row.loginNo;
  ruleForm.enterTime = row.enterTime;
  ruleForm.avatar = row.avatar;
  ruleForm.birthday = row.birthday;
  ruleForm.email = row.email;
  ruleForm.qrCode = row.qrCode;
  console.log(ruleForm, "ruleForm");
};
function editRoleInfo() {
  console.log(ruleForm, "ruleForm");
  editRole({
    userName: ruleForm.userName,
    phoneNum: ruleForm.phoneNum,
    roleId: ruleForm.roleIds.join(","), // 编辑时也需要转换格式
    gender: ruleForm.gender,
    loginNo: ruleForm.loginNo,
    enterTime: ruleForm.enterTime,
    avatar: ruleForm.avatar,
    birthday: ruleForm.birthday,
    email: ruleForm.email,
    qrCode: ruleForm.qrCode,
    id: editId.value
  }).then((res: any) => {
    console.log(res);
    addRoleDialogVisible.value = false;
    ElMessage({
      type: "success",
      message: res.message
    });
    queryListTableData();
  });
}

const handleDeteleRole = async (record: Recordable) => {
  // const type = await VxeUI.modal.confirm("您确定要删除吗？");
  ElMessageBox.confirm("确认是否删除?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      removeAgentByAgent({ userId: record.id }).then((res: any) => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        queryListTableData();
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "删除失败"
      // });
    });
};
//重置用户密码

const resetPassword = async (record: Recordable) => {
  // const type = await VxeUI.modal.confirm("您确定要删除吗？");
  ElMessageBox.confirm("确认重置用户密码?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      resetRolePassword({ userId: record.id }).then((res: any) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "重置成功"
          });
          queryListTableData();
        } else {
          ElMessage.error(res.msg);
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "删除失败"
      // });
    });
};
//重置添加用户
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryListTableData(val);
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryListTableData(val);
};
function handleClose() {
  console.log("关闭");
  addRoleDialogVisible.value = false;
}
// 头像上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ruleForm.avatar = response.data.dataUrl;
    ElMessage.success("上传成功");
    
    // ruleForm.avatar = URL.createObjectURL(uploadFile.raw!);
    previewUrl.value = response.data.previewUrl;
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 二维码上传成功的回调
const handleQrCodeSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    // ruleForm.qrCode = URL.createObjectURL(uploadFile.raw!);
    ruleForm.qrCode = response.data.dataUrl;
    previewQrCodeUrl.value = response.data.previewUrl;
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 二维码上传前的校验
const beforeQrCodeUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("二维码图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("二维码图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>
<template>
  <div class="statement">
    <div class="search">
      <div class="c-input">
        <el-input
          v-model="queryParams.userName"
          clearable
          placeholder="请输入姓名"
        />
      </div>
      <div class="c-input">
        <el-input
          v-model="queryParams.phoneNum"
          clearable
          placeholder="请输入手机号"
        />
      </div>
      <div class="c-input">
        <el-select
          v-model="queryParams.roleId"
          size="large"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="search-btn">
        <el-button type="primary" size="large" @click="queryListTableData"
          >查询</el-button
        >
        <el-button size="large" @click="onReset">重置</el-button>
      </div>
    </div>
    <div class="add">
      <el-button type="primary" size="large" @click="handleAddRole('add')"
        ><el-icon><Plus /></el-icon>添加用户</el-button
      >
    </div>
    <div class="c-page__bg">
      <el-table :data="tableData">
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="phoneNum" label="手机号码" />
        <el-table-column width="220" prop="genderName" label="性别" />
        <el-table-column width="180" label="角色名称">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.roles" :key="index"
              >{{ item.roleName
              }}<i v-if="index != scope.row.roles.length - 1">,</i></span
            >
          </template>
        </el-table-column>
        <el-table-column prop="loginNo" label="登录账号" />
        <el-table-column prop="enterTimeStr" label="录入时间" />
        <el-table-column #default="{ row }" label="操作">
          <span class="c-text-primary" @click="handleEditRole(row, 'edit')"
            >编辑</span
          >
          <span class="c-text-primary" @click="handleDeteleRole(row)">
            删除
          </span>
          <span class="c-text-primary" @click="resetPassword(row)">
            重置密码
          </span>
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addRoleDialogVisible"
      title="添加用户"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            v-model="ruleForm.phoneNum"
            type="phoneNum"
            autocomplete="off"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input
            v-model="ruleForm.userName"
            type="text"
            autocomplete="off"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <!-- <el-form-item label="是否删除" prop="deleteFlag">
          <el-radio-group v-model="ruleForm.deleteFlag">
            <el-radio
              v-for="item in deleteFlagList"
              :key="item.code"
              :label="item.code"  >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="账号" prop="loginNo">
          <el-input
            v-model="ruleForm.loginNo"
            type="text"
            autocomplete="off"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="ruleForm.gender"
            size="large"
            placeholder="请选择性别"
          >
            <el-option
              v-for="item in genderList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="ruleForm.roleIds"
            size="large"
            multiple
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="录入时间" prop="enterTime">
          <el-date-picker
            v-model="ruleForm.enterTime"
            size="large"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="time => time > Date.now()"
            placeholder="请选择录入时间"
          />
        </el-form-item>

        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="ruleForm.birthday"
            size="large"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="ruleForm.email"
            type="email"
            autocomplete="off"
            placeholder="请输入邮箱"
          />
        </el-form-item>

        <!-- <el-form-item label="密码" prop="loginPass">
          <el-input
            v-model="ruleForm.loginPass"
            type="password"
            autocomplete="off"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item> -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :data="{ type: 'avatar' }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
          <img
              v-if="ruleForm.avatar && !previewUrl"
              :src="ruleForm.avatar"
              class="avatar"
            />
            <img v-else-if="previewUrl" :src="previewUrl" class="avatar" />
            <div v-else>
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="upload-text">请上传头像</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="微信二维码" prop="qrCode">
          <el-upload
            class="qrcode-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :data="{ type: 'qrcode' }"
            :on-success="handleQrCodeSuccess"
            :before-upload="beforeQrCodeUpload"
          >
            <img v-if="ruleForm.qrCode && !previewQrCodeUrl" :src="ruleForm.qrCode" class="qrcode" />
            <img v-else-if="previewQrCodeUrl" :src="previewQrCodeUrl" class="qrcode" />
            <div v-else>
              <el-icon class="qrcode-uploader-icon"><Plus /></el-icon>
              <div class="upload-text">请上传微信二维码</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="  " style="margin-top: 30px">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.statement {
  height: 100%;
  overflow: hidden;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .c-input {
    width: 240px !important;
    margin-bottom: 16px;
    margin-right: 16px;
    --el-border-radius-base: 8px;
    --el-input-focus-border-color: var(--main-color) !important;
    --el-component-size: 40px;
  }

  .search-btn {
    padding-left: 15px;
    .c-btn {
      height: 38px;
      border-radius: 8px;
      box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.c-page__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
.c-drawer-form {
  .c-info__title {
    margin-top: 20px;
    margin-bottom: 20px;
    color: #262626;
    font-size: 16px;
  }
  .el-form-item {
    margin-left: 60px;
    margin-bottonm: 10px;
  }
}
.el-drawer__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 0;
}
.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

// ... 上传图片 ...

.avatar-uploader,
.qrcode-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.required-label::before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

// ... 其他样式 ...
.qrcode-uploader-icon,
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 100px;
}

.qrcode,
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
